<?php


namespace App\Controller\Frontend;


use App\Entity\PageTag;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class CommonController extends AbstractController {

    /**
     * 404
     * @Route("/common/404", name="not_found_page")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function notFound () {
        return $this->render('frontend/common/404.html.twig', []);
    }

    /**
     * 维护
     * @Route("/common/maintenance", name="maintenance_page")
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function maintenance () {
        return $this->render('frontend/common/maintenance.html.twig', []);
    }

    /**
     * 类别页
     * @param Request $request
     * @param EntityManagerInterface $em
     * @param PaginatorInterface $paginator
     * @Route("/common/search", name="search_page")
     * @return array|\Symfony\Component\HttpFoundation\Response
     */
    public function search (Request $request, EntityManagerInterface $em, PaginatorInterface $paginator) {
        $keyword = $request->get('keyword', null);

        $dql = "SELECT p.id,p.title,p.thumbnail,p.publish_time,p.page_like,p.page_tags,p.summary,c.value as category,a.avatar,a.username,a.nickname
                from App\Entity\Page as p 
                left join App\Entity\PageCategory as c with p.page_category_id = c.id 
                left join App\Entity\AdminUser as a with p.admin_user_id = a.id 
                where p.status = 1 and p.title like '%".$keyword."%' order by p.id DESC ";

        $query = $em->createQuery($dql);
        $pagination = $paginator->paginate($query, $request->query->getInt('page', 1), 10);

        // 获取对应标签
        $page_tags = $this->getDoctrine()->getRepository(PageTag::class)->findAllToArray();
        $pages = $pagination->getItems();
        foreach ($pages as &$page) {
            $items = [];
            foreach ($page['page_tags'] as $tag_id) {
                if (isset($page_tags[$tag_id])) {
                    array_push($items, $page_tags[$tag_id]);
                }
            }
            $page['page_tags'] = $items;
        }
        $pagination->setItems($pages);

        return $this->render('frontend/common/search.html.twig', [
            'keyword'   => $keyword,
            'pagination' => $pagination,
        ]);
    }
}